import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login'
import Layout from '../views/Layout'
import Home from '../views/Home'
import Article from '../views/Article'
import Publish from '../views/Publish'
import { getItem } from '../utils/auth'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    alias: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/layout',
    component: Layout,
    redirect: '/layout/home',
    children: [
      {
        path: '/layout/home',
        // alias: 别名
        // alias: '/layout',
        name: 'Home',
        component: Home
      },
      {
        path: '/layout/article',
        component: Article
      },
      {
        path: '/layout/publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航前置守卫
router.beforeEach((to, from, next) => {
  Nprogress.start()
  if (getItem()) {
    if (to.path.toLowerCase() === '/' || to.path.toLowerCase() === '/login') {
      next('/layout/home')
    } else {
      next()
    }
  } else {
    if (to.path.toLowerCase() === '/' || to.path.toLowerCase() === '/login') {
      next()
    } else {
      next('/login')
    }
  }
  Nprogress.done()
})
// 导航后置守卫
router.afterEach((to, from) => {
  // console.log(to, from)
  Nprogress.done()
})
export default router
